'use strict';

const db = uniCloud.database();
const uniIdCommon = require('uni-id-common');

exports.main = async (event, context) => {
  // 1. 获取 token
  const token = context.uniIdToken || event.uniIdToken || (event.args && event.args.uniIdToken);
  if (!token) {
    return { code: 401, msg: '未登录' };
  }
  // 2. 解析 token
  const uniId = uniIdCommon.createInstance({ context });
  const tokenRes = await uniId.checkToken(token);
  if (tokenRes.code !== 0) {
    return { code: 401, msg: 'token无效或已过期' };
  }
  
  // 3. 确定要查询的用户ID
  const targetUserId = event.userId || event.args?.userId;
  const uid = targetUserId || tokenRes.uid; // 如果指定了userId则查询指定用户，否则查询当前用户
  
  console.log('【getUserInfo】查询用户信息:', { 
    targetUserId, 
    currentUserId: tokenRes.uid, 
    finalUid: uid 
  });
  
  // 4. 查询用户信息
  const userRes = await db.collection('uni-id-users').doc(uid).get();
  if (!userRes.data || userRes.data.length === 0) {
    return { code: 404, msg: '用户不存在' };
  }
  
  console.log('【getUserInfo】返回用户信息:', { 
    uid, 
    nickname: userRes.data[0].nickname || userRes.data[0].username,
    hasAvatar: !!(userRes.data[0].avatar_file && userRes.data[0].avatar_file.url)
  });
  
  return {
    code: 200,
    data: userRes.data[0]
  };
}; 